package com.yunhui.util;

import com.yunhui.entity.User;
import org.apache.velocity.shaded.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * 文件上传工具类，上传到本地文件
 * @author wgh
 *
 */
public class UserImgFile {


    public User getName(MultipartFile head , User user) {

        String path = null;


        //System.out.println(1);
        if (head != null) {
            //定义文件促存放的文件夹
            //D:\RuanJianGongJu\idea\idea 2019\ideaWork\travel\target\classesstatic/images/
            try {

                path = new File("").getCanonicalPath() + "/target/classes/static/img/user_head";
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取上传的文件名
            String imgName = head.getOriginalFilename();
            //System.out.println(imgName);
            //获取文件后缀名
            String suffix = FilenameUtils.getExtension(imgName);

            //根据后缀名判断是否是图片
            if (suffix.equalsIgnoreCase("png")
                    || suffix.equalsIgnoreCase("jpg")
                    || suffix.equalsIgnoreCase("jpeg")
                    || suffix.equalsIgnoreCase("pneg")) {
                //设置上传后的文件存放名
                //1~1000的随机数+当前时间毫秒数+后缀名

                user.setImgname(user.getName()+ System.currentTimeMillis());
                String filePath =user.getImgname() + "." + suffix;
                //静态文件路径
                user.setImgurl("../img/user_head/" + filePath);

                File file = new File(path, filePath);
                //判断文件是否存在
                if (!new File(path).exists()) {
                    new File(path).mkdirs();//不存在就创建
                }
                try {
                    head.transferTo(file);  //将上传过来的文件通过创建的IO流存入
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }


        }
        return user;
    }
}